package service

import (
	"code.huawei.com/tdc-sdk/mgmt"
	"code.huawei.com/tdc-sdk/tdcsdk"
	"code.huawei.com/tdc-sdk/utils"
	"nft-server/config"
	"nft-server/logger"
)

var (
	sdk *tdcsdk.TDCSDK
)

func init() {
	var err error
	sdk, err = tdcsdk.New(config.GetConfig().DACConfig.ConfigPath)
	if err != nil {
		logger.Error("Init DAC sdk error: %v", err)
	}
}

func NFTTransfer(collectionIndex, from, to, tokenId string) (txid string, err error) {
	return sdk.TransferFrom(collectionIndex, from, to, tokenId)
}
func NFTApprove(collectionIndex, operator, tokenId string) (txid string, err error) {
	return sdk.Approve(collectionIndex, operator, tokenId)
}
func NFTGetApproved(collectionIndex, tokenId string) (string, error) {
	return sdk.GetApproved(collectionIndex, tokenId)
}

func IsMinted(collectionIndex, tokenId string) (bool, error) {
	return sdk.IsMinted(collectionIndex, tokenId)
}

func GenerateIdentity(name string) (cert, key, addr string, err error) {
	cert, key, addr, err = sdk.GenerateIdentity(utils.EcdsaWithSha256, name)
	if err != nil {
		return "", "", "", err
	}
	return cert, key, addr, err
}

func NFTOwnerOf(collectionIndex, tokenId string) (identity string, err error) {
	return sdk.OwnerOf(collectionIndex, tokenId)
}

func SwitchIdentityWithPem(cert, sk string) error {
	return sdk.SwitchIdentityWithPem(utils.EcdsaWithSha256, cert, sk)
}

//增加获取链上所有集合名字--暂时不用
func GetCollectionNamesOnChain() ([]string, error) {
	return sdk.Collections()
}

//根据集合标识符和数字资产编号生成数字资产编码，同样具备唯一性，
//可用于可视化展示和DAC产品页核验-nft721
func GenerateAssetID(collectionIndex, tokenId string) string {
	return sdk.GenerateAssetID(collectionIndex, tokenId)
}

func GetTokenURI(collectionIndex, tokenId string) (*mgmt.Metadata, error) {
	metadata, err := sdk.TokenURI(collectionIndex, tokenId)
	if err != nil {
		return nil, err
	}
	return metadata, nil
}
